/**
 * @description  因子收益贡献
 * @author zls
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Row, Col } from 'antd';
import { ThreeHeaderC, TableC } from '../../../../comps';

class FactorIncomeContribution extends PureComponent {
  constructor() {
    super();
    this.state = {
      tableData: { data1: { columns: [], dataSource: undefined }, data2: { columns: [], dataSource: undefined } },
    };
  }
  componentDidMount() {
    const { dispatch, args } = this.props;
    this.getData(args);
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    const { dispatch, args } = nextProps;
    if (JSON.stringify(args) !== JSON.stringify(this.props.args)) {
      this.setState({ tableData: { data1: { columns: [], dataSource: undefined }, data2: { columns: [], dataSource: undefined } } });

      this.getData(args);
    }
  }

  getData = (args) => {
    this.props.dispatch({
      type: 'attributionAnalysisM/getFactorContributionDetail',
      payload: args,
      callback: (res) => {
        this.setState({ tableData: res?.data });
      },
    });
  };

  showTable = (data) => {
    const { columns = [], dataSource } = data || {};

    const newColumns = columns.map((x) => {
      if (['factor'].indexOf(x.key) > -1) {
        return {
          ...x,
        };
      }
      if (['return_contribution'].indexOf(x.key) > -1) {
        return {
          ...x,
          type: 'rate',
          toFixed: 4,
          width: '50%',
          sorter: (a, b) => a.return_contribution - b.return_contribution,
        };
      }

      return x;
    });
    const style = {
      width: '50%',
      textAlign: 'right',
    };
    const arr = dataSource?.concat();
    const item = arr?.pop();
    return (
      <div>
        <TableC columns={newColumns} dataSource={arr} scroll={{ y: 400 }} hidePage={true} rowKey='factor'></TableC>
        {arr?.length > 0 && (
          <div className='ant-table' style={{ width: 'calc(100% - 8px)' }}>
            <div className='ant-table-tbody'>
              <tr className='ant-table-row' style={{ display: 'flex', fontWeight: 600 }}>
                <td style={{ flex: 1 }}>{item?.factor || '--'}</td>
                <td style={style}>{item?.return_contribution ? `${(item?.return_contribution * 100).toFixed(4)}%` : '--'}</td>
              </tr>
            </div>
          </div>
        )}
      </div>
    );
  };

  render() {
    const { tableData = {} } = this.state;
    const { data1, data2 } = tableData;
    return (
      <div>
        <Row gutter={16}>
          <Col span={12}>
            <ThreeHeaderC title='风格因子' />
            <div style={{ marginTop: '10px' }}>{this.showTable(data2)}</div>
          </Col>
          <Col span={12}>
            <ThreeHeaderC title='行业因子' />
            {this.showTable(data1)}
          </Col>
        </Row>
      </div>
    );
  }
}
export default connect(({ attributionAnalysisM }) => ({
  attributionAnalysisM,
}))(FactorIncomeContribution);
